package org.abc.fund.controller.auth;

import jakarta.validation.Valid;
import org.abc.fund.service.auth.request.LoginRequest;
import org.abc.fund.controller.user.response.UserResponse;
import org.abc.fund.entity.user.User;
import org.abc.fund.service.auth.AuthService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

  private final AuthService authService;

  public AuthController(AuthService authService) {
    this.authService = authService;
  }

  @PostMapping("/login")
  public ResponseEntity<?> loginUser(@Valid @RequestBody LoginRequest loginRequest) {
    Optional<User> userOptional =
        authService.authenticate(loginRequest.getUsername(), loginRequest.getPassword());

    if (userOptional.isPresent()) {
      User user = userOptional.get();
      return ResponseEntity.ok(UserResponse.fromEntity(user));
    } else {
      return ResponseEntity.status(401).body("错误：用户名或密码不正确");
    }
  }

  @PostMapping("/logout")
  public ResponseEntity<?> logoutUser() {
    return ResponseEntity.ok("用户已成功登出");
  }
}
